<?php
/**
 * @file			admin.ctrl.php
 * @CopyRight		(C)1996-2099 SINA Inc.
 * @Project			Waitan
 * @Author			guanghui <guanghui1@staff.sina.com.cn>
 * @Create Date:	2011-08-12
 * @Modified By:	guanghui/2011-08-12
 * @Brief			Admin Index
 */

include(P_ADMIN_MODULES . '/admin.base.php');

class admin_ctrl extends admin_base {
	
	/**
	* 超级权限
	*/
	const SUPER_PERMISSION = 999;
	
	/**
	* 后台管理菜单
	*/
	private $_nav = null;
	
	/**
	* 设置导航菜单
	* 
	*/
	private function _setNav()
	{
		$this->_nav = array(
						'系统管理' => array(
											'nav_qx' => array(6),
											'menus' => array(
												array(
													'menu_qx' => array(6),
													'menu_name' => '后台帐号管理',
													'menu_list' => array(
														array('qx' => 6, 'name' => '后台帐号管理', 'link' => URL('admin/admin.userList'))
													)
												)
											)
										)
					);
	}
	
	function default_action()
	{
		APP::redirect('admin/admin.userList', 2);
	}
	
	/**
	* 空白页
	* 
	*/
	function blank() {}
	
	/**
	* 管理员列表
	* 
	*/
	function userList()
	{
		$userList = APP::MOD('admin')->getList();
		$userList = $userList['rst'];
		
		TPL::assign('userList', $userList);
		$this->_display();
	}
	
	/**
	* 管理员登录后首页
	* 
	*/
	function index()
	{
		$this->_setNav();
		TPL::assign('superAdmin', $this->_superAdmin);
		TPL::assign('nav', $this->_nav);
		$this->_display();
	}
	
	/**
	 * 登录JSON
	 * @param type $state
	 * @param type $msg 
	 */
	private function _ajaxRst($state, $msg = '')
	{
		header('Content-type: application/json');
		$rst = array('state' => $state);
		if ($msg) {
			$rst['msg'] = $msg;
		}
		echo json_encode($rst);
		exit;
	}
	
	/**
	* 管理员登录
	* 
	*/
	public function login()
	{
		if ($this->_isPost()) {
			$this->_checkReferer();
			
			$name = trim(V('p:username', ''));
			$pwd = trim(V('p:password', ''));
			$verify_code = strtolower(V('p:verify_code', ''));
			
			if (empty($name) || empty($pwd)) {
				$this->_ajaxRst('401', '帐号或密码错误');
				//exit('{"state":"401", "msg":"帐号或密码错误"}');
			}
			
			//检查验证码
			if(IS_USE_CAPTCHA) {
				$autoCode = APP :: N('authCode');
				if (!$autoCode->checkAuthcode($verify_code)) {
					$this->_ajaxRst('402', '验证码错误');
					//exit('{"state":"402", "msg":"验证码错误"}');
				}
			}
			
			$userInfo = APP::MOD('admin')->getInfoByName($name);
			$userInfo = $userInfo['rst'];
			
			if (!is_array($userInfo) || empty($userInfo) || $userInfo['pwd'] !== $this->_getPwdString($pwd, $userInfo['pwd_rand'])) {
				$this->_ajaxRst('401', '帐号或密码错误');
				//exit('{"state":"401", "msg":"帐号或密码错误"}');
			}
			
			if (!in_array($userInfo['admin_id'], $this->_superAdmin) && empty($userInfo['permissions'])) {
				$this->_ajaxRst('401', '账号权限未设置');
			}
			
			$admin_id = $userInfo['admin_id'];
			$admin_name = $userInfo['username'];
			$permissions = $userInfo['permissions'];
			
			//$rst = APP::MOD('admin')->saveInfo(array('last_login' => APP_LOCAL_TIMESTAMP), $admin_id);
			
			$this->_initAdminSess($admin_id, $admin_name, $permissions, $userInfo['group_id']);
			
			$this->_ajaxRst('200');
			//exit('{"state":"200"}');
		}
		$this->_display();
	}
	
	/**
	* 退出登录
	* 
	*/
	public function logout()
	{
		$this->_resetAdminSess();
		APP::redirect('admin/admin', 2);
	}
	
	/**
	* 修改密码
	* 
	*/
	public function rePwd()
	{
		if ($this->_isPost()) {
			$this->_checkReferer();
			
			$oldPwd = V('p:old_pwd', '');
			$newPwd = V('p:pwd', '');
			$reNewPwd = V('p:re_pwd', '');
			
			if (empty($oldPwd) || empty($newPwd)) {
				APP::ajaxRst(false, '80010001', 'Parameter can not be empty');
				exit;
			}
			
			if ($newPwd !== $reNewPwd) {
				APP::ajaxRst(FALSE, '500400001', '两次输入的新密码不相同');
				exit;
			}
			
			if ($newPwd === $oldPwd) {
				APP::ajaxRst(FALSE, '500400001', '新密码不能与旧密码相同');
				exit;
			}
			
			$admin_id = USER::aid();
			$userInfo = APP::MOD('admin')->getInfoById($admin_id);
			$userInfo = $userInfo['rst'];
			
			if (!is_array($userInfo) || empty($userInfo)) {
				APP::ajaxRst(FALSE, '400000000', '帐号不存在');
				exit;
			}
			
			if ($this->_getPwdString($oldPwd, $userInfo['pwd_rand']) !== $userInfo['pwd']) {
				APP::ajaxRst(FALSE, '500400001', '输入的旧密码错误');
				exit;
			}
			
			$new_rand = $this->_getRandStr(5);
			$rst = APP::MOD('admin')->saveInfo(array('pwd' => $this->_getPwdString($newPwd, $new_rand), 'pwd_rand' => $new_rand), $admin_id);
			if ($rst['rst']) {
				APP::ajaxRst(TRUE);
			} else {
				APP::ajaxRst(FALSE, '500400001', '修改失败，请重试！');
			}
		}
		APP::ajaxRst(FALSE, '500404001', '错误的访问方式');
		exit;
	}
	
	/**
	* 添加管理员帐号
	* 
	*/
	public function addAdmin()
	{
		if ($this->_isPost()) {
			$this->_checkReferer();
			
			$username = trim(V('p:username', ''));
			$pwd = trim(V('p:pwd', ''));
			$rePwd = trim(V('p:re_pwd', ''));
			$permissions = V('p:permissions', '');
			
			if ($username === '') {
				APP::ajaxRst(FALSE, '500400001', '帐号名不能为空');
				exit;
			}
			
			if ($pwd !== $rePwd) {
				APP::ajaxRst(FALSE, '500400001', '两次输入密码不一致');
				exit;
			}
			
			if (!is_array($permissions) || empty($permissions)) {
				APP::ajaxRst(FALSE, '500400003', '请选择用户权限');
			}
			
			//检查是否重复帐号
			$userInfo = APP::MOD('admin')->getInfoByName($username);
			$userInfo = $userInfo['rst'];
			if (is_array($userInfo) && !empty($userInfo)) {
				APP::ajaxRst(FALSE, '500400001', '该帐号名已存在');
				exit;
			}
			
			$rand = $this->_getRandStr(5);
			$data = array(
						'username' => $username,
						'pwd' => $this->_getPwdString($pwd, $rand),
						'pwd_rand' => $rand,
						'state' => 1,
						'add_time' => APP_LOCAL_TIMESTAMP,
						'opt_user' => USER::getAdmin(ADMIN_SESSION_UNAME),
						'permissions' => implode('|', $permissions),
						'group_id'	=> (int)V('p:group_id', 0)
					);
			$rst = APP::MOD('admin')->saveInfo($data);
			if ($rst['rst']) {
				APP::ajaxRst(TRUE);
			} else {
				APP::ajaxRst(FALSE, '500500001', '添加失败，请重试！');
			}
			exit;
		}
		
		$this->_setNav();
		TPL::assign('nav', $this->_nav);
		TPL::assign('permissions', $this->_permissions);
		$this->_display();
	}
	
	/**
	* 删除一个管理员帐号
	* 
	*/
	function delAdmin()
	{
		$this->_checkReferer();
		
		$admin_id = (int)V('p:admin_id', 0);
		if (empty($admin_id)) {
			APP::ajaxRst(false, '80010001', 'Parameter can not be empty');
			exit;
		}
		
		if ($admin_id == USER::aid()) {
			APP::ajaxRst(FALSE, '400400000', '不能删除自身帐号');
			exit;
		}
		
		$rst = APP::MOD('admin')->delAdmin($admin_id);
		if ($rst['rst']) {
			APP::ajaxRst(TRUE);
		} else {
			APP::ajaxRst(FALSE, '500500001', '删除失败，请重试！');
		}
		exit;
	}
	
	/**
	* 设置管理员权限
	* 
	*/
	function setPermissions()
	{
		if ($this->_isPost()) {
			$this->_checkReferer();
			
			$aid = (int)V('p:aid', 0);
			$permissions = V('p:permissions', '');
			
			if (empty($aid) || !is_array($permissions) || empty($permissions)) {
				APP::ajaxRst(FALSE, '9999999', '参数错误');
			}
			
			$data = array('group_id'  => V('p:group_id'),
						'permissions' => implode('|', $permissions)
					);
			$rst = APP::MOD('admin')->saveInfo($data, $aid);
			if ($rst['rst']) {
				APP::ajaxRst(TRUE);
			} else {
				APP::ajaxRst(FALSE, '500500001', '添加失败，请重试！');
			}
			exit;
		}
		
		$aid = (int)V('g:aid', 0);
		if (empty($aid))	APP::redirect(URL('admin/admin.userList'), 3);
		
		$adminInfo = APP::MOD('admin')->getInfoById($aid);
		$adminInfo = $adminInfo['rst'];
		if (!is_array($adminInfo) || empty($adminInfo)) {
			APP::redirect(URL('admin/admin.userList'), 3);
		}
		
		$this->_setNav();
		TPL::assign('nav', $this->_nav);
		TPL::assign('permissions', $this->_permissions);
		TPL::assign('adminInfo', $adminInfo);
		$this->_display();
	}
	
	/**
	* 产生指定长度的随机码
	* 
	* @param mixed $len
	*/
	private function _getRandStr($len = 5)
	{
		$baseChar = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
		$str = '';
		while (strlen($str) < $len) {
			$cursor = mt_rand(0, strlen($baseChar) - 1);
			$str .= substr($baseChar, $cursor, 1);
		}
		return $str;
	}
	
	/**
	* 获取最终的用户密码
	* 
	* @param 原始密码明文 $pwd
	* @param 加密随机码 $pwd_rand
	* @return string
	*/
	private function _getPwdString($pwd, $pwd_rand)
	{
		return md5(substr(md5($pwd) . md5($pwd_rand), 14, 30));
	}
}
